// 云函数入口文件
const cloud = require('wx-server-sdk')
var rq = require('request-promise')

cloud.init()

// 随机返回一条
// http://api.avatardata.cn/MingRenMingYan/Random?key=768bc6c162bb442e9158395ce44d5176

// 查询相关名人名言
// http://api.avatardata.cn/MingRenMingYan/LookUp?key=768bc6c162bb442e9158395ce44d5176&keyword=%E7%BE%8E%E4%B8%BD&page=1&rows=10

// 云函数入口函数
exports.main = async(event, context) => {
  switch (event.action) {
    case 'getRandomSaying':
      {
        return getRandomSaying(event)
      }
      break;
    case 'searchKeySayings':
      {
        return searchKeySayings(event)
      }
      break;
    default:
      return "请传入action值。包括：getRandomSaying、searchKeySayings"
  }
}

//随机返回一条名人名言
async function getRandomSaying(event) {
  const log = cloud.logger()
  var url = 'http://api.avatardata.cn/MingRenMingYan/Random?key=768bc6c162bb442e9158395ce44d5176';
  log.error({
    vurl: url
  })
  var res = rq(url).then(html => {
    return html;
  }).catch(err => {
    console.log(err);
  })
  return res
}

//搜索相关名人名言
async function searchKeySayings(event) {
  const log = cloud.logger()
  var page = event.page;
  var rows = event.rows;
  var keyword = event.keyword;
  if (page == null) {
    page = 1;
  }
  if (rows == null) {
    rows = 20;
  }
  if (keyword == null) {
    return "请传入keyword"
  }
  url = 'http://api.avatardata.cn/MingRenMingYan/LookUp?key=768bc6c162bb442e9158395ce44d5176&page=' + page + "&rows=" + rows;
  log.error({
    vurl: url
  })
  var options = {
    method: 'POST',
    uri: url,
    form: {
      keyword: keyword
    },
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  };
  var res = rq(options).then(html => {
    return html;
  }).catch(err => {
    console.log(err);
  })
  return res
}